package com.rd.student.dashuju.zhengruixian.test0726;

public class TestTicket1 implements Runnable{
    int ticketsNum=100;
    //因为在创建线程时 我们传进去的是同一个ticket对象
    //所以线程共享多个ticketNum
    //所以多个线程共享obj
    //这是一个被多线程共享的对象
    //这个Object只是加锁时使用的对象
    Object obj=new Object()
            ;
    @Override
    public void run(){
        while (true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj){
                if (ticketsNum<=0){
                    System.out.println("票卖光了");
                    return;
                }
                System.out.println(Thread.currentThread().getName()+"出票"+ticketsNum );
                ticketsNum--;
            }
        }
    }

    public static void main(String[] args) {
        TestTicket1 ticket1=new TestTicket1();
        Thread t1=new Thread(ticket1);
        Thread t2=new Thread(ticket1);
        Thread t3=new Thread(ticket1);
        Thread t4=new Thread(ticket1);
        Thread t5=new Thread(ticket1);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
}
